﻿package 
{
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.text.TextField;
	import flash.display.SimpleButton;
	import flash.events.KeyboardEvent;
	import flash.ui.Mouse;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.media.Sound;
	import flash.utils.Timer;
	
	//BlockMap의 움직임을 관리하는 클래스
	public class Menu_InGame extends MovieClip 
	{
		
		public static var GameTime:Number;
		public static var UI:Menu_InGame;
		
		
		public var readyGo;
		private var time:Number;
		
		
		
		
		private var effect_Warning;
		
		public var scoreTimer:Timer;
		private var scoreUPS:Number;
		private var scoreCopy:Number;
		
		private var timeWarning;
		private var timeWarning_begin;
		
		private var pointSignShown:Array;
		private var pointSignEffect:*;
		private var signScoreIndex:int;
		private const SCORE_TABLE = [500, 1000, 3000, 5000, 10000, 20000, 30000, 50000, 70000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1500000, 2000000, 2500000, 3000000, 3500000, 4000000, 4500000, 5000000];
		
		public static var cubeKind:int;
		private var cubeEffect:*;
		
		private var doubleChanceEffect:*;
		
		public static var isPaused:Boolean;
		
		public static var EffectLevel:Sprite;
		
		public static var isBonusTime:Boolean;
		
		public static var gameOver:Boolean;
		
		//private var blockMap:BlockMap;
		
		public function Menu_InGame(){	
			
			addEventListener(Event.ADDED_TO_STAGE, init, false, 0, true);
			
		}
		
		private function init(e:Event = null):void 
		{
			// entry point
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			UI = this;
			
			isBonusTime = false;
			gameOver = false;
			
			GUI_Cursor.cursor.setCursor(0);
			
			cubeKind = 0;
			Clickr.bestScored = false;	//여기서 초기화
			
			bestScoreTXT.text = Clickr.makeCurrency(Clickr.bestScore);
			
			pointSignShown = [false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false];
			
			isPaused = true;
			signScoreIndex = 0;
			
			addEventListener(Event.ENTER_FRAME, Update, false, 0, true);
			
			addEventListener(CustomEvent.SCORE_UP, scoreUp, false, 0, true);
			addEventListener(CustomEvent.COMBO_PLUS, comboPlusHandler, true, 0, true);
			
			
			blockMap.addEventListener(CustomEvent.DOUBLE_CHANCE_START, onDoubleChance, false, 0, true);
			blockMap.addEventListener(CustomEvent.DOUBLE_CHANCE_SUCCESS, onDoubleChance, false, 0, true);
			blockMap.addEventListener(CustomEvent.DOUBLE_CHANCE_FAIL, onDoubleChance, false, 0, true);
			blockMap.addEventListener(CustomEvent.BONUS_OVER, onBonusOver, false, 0, true);
			
			Quit.addEventListener(MouseEvent.CLICK, onClickPause, false, 0, true);
			Retry.addEventListener(MouseEvent.CLICK, onClickRetry, false, 0, true);
			
			RotateL.addEventListener(MouseEvent.CLICK, onClickRotateL, false, 0, true);
			RotateR.addEventListener(MouseEvent.CLICK, onClickRotateR, false, 0, true);
			
			
			blockMap.addEventListener(CustomEvent.ROTATE_LEFT, onRequestRotateL, false, 0, true);
			blockMap.addEventListener(CustomEvent.ROTATE_RIGHT, onRequestRotateR, false, 0, true);
			
			
			blockMap.addEventListener(NavigationEvent.RESTART, onRequestRestart, false, 0, true);
			
			//stage.addEventListener(KeyboardEvent.KEY_DOWN, onKey);
			
			mouseEnabled = false;
			
			//UI보다 아래 가야 하므로 원래부터 있게 함
			
			
			EffectLevel = new Sprite();
			//EffectLevel.x = 250;
			//EffectLevel.y = 25;
			EffectLevel.mouseEnabled = false;
			EffectLevel.mouseChildren = false;
			
			addChild(EffectLevel);
			
			
			readyGo = new Effect_ReadyGo();
			readyGo.x = 430;
			readyGo.y = 205;
			EffectLevel.addChild(readyGo);
			
			
			
			GameTime = 3602;
			//GameTime = 600;
			
			
		}
		
		public function dispose(){
			trace("dispose called");
			
			blockMap.removeEventListener(CustomEvent.DOUBLE_CHANCE_START, onDoubleChance);
			blockMap.removeEventListener(CustomEvent.DOUBLE_CHANCE_SUCCESS, onDoubleChance);
			blockMap.removeEventListener(CustomEvent.DOUBLE_CHANCE_FAIL, onDoubleChance);
			blockMap.removeEventListener(CustomEvent.BONUS_OVER, onBonusOver);
			blockMap.removeEventListener(CustomEvent.ROTATE_LEFT, onRequestRotateL);
			blockMap.removeEventListener(CustomEvent.ROTATE_RIGHT, onRequestRotateR);
			blockMap.removeEventListener(NavigationEvent.RESTART, onRequestRestart);
			
			blockMap.dispose();
			
			removeObject(readyGo);
			removeObject(blockMap);
			removeObject(effect_Warning);
			removeObject(timeWarning);
			removeObject(timeWarning_begin);
			removeObject(pointSignEffect);
			removeObject(cubeEffect);
			removeObject(doubleChanceEffect);
			
			blockMap = null;
			
			//다른 상황 관련 object도여기서 삭제
			
			if (this.hasEventListener(CustomEvent.SCORE_UP)) {
				removeEventListener(CustomEvent.SCORE_UP, scoreUp);
			}
			if (this.hasEventListener(NavigationEvent.RESTART)) {
				removeEventListener(NavigationEvent.RESTART, onRequestRestart);
			}
			if(this.hasEventListener(Event.ENTER_FRAME)){
				removeEventListener(Event.ENTER_FRAME, Update);
			}
			if (this.hasEventListener(CustomEvent.COMBO_PLUS)) {
				removeEventListener(CustomEvent.COMBO_PLUS, comboPlusHandler);
			}
			
			Quit.removeEventListener(MouseEvent.CLICK, onClickPause, false);
			Retry.removeEventListener(MouseEvent.CLICK, onClickRetry, false);
			RotateL.removeEventListener(MouseEvent.CLICK, onClickRotateL, false);
			RotateR.removeEventListener(MouseEvent.CLICK, onClickRotateR, false);
			/*
			removeChild(RotateL);
			removeChild(RotateR);
			removeChild(Retry);
			removeChild(Quit);
			removeChild(scoreTXT);
			removeChild(bestScoreTXT);
			removeChild(blockMap);
			removeChild(timeline);
			removeChild(_countDown);
			
			RotateL = null;
			RotateR = null;
			Retry = null;
			Quit = null;
			scoreTXT = null;
			bestScoreTXT = null;
			blockMap = null;
			timeline = null;
			_countDown = null;
			*/

		}
		
		private function Update(e:Event):void {
			if (isPaused) return;
			
			if(GameTime >= -120){
				if (GameTime == 1) {
					blockMap.blockEvent();
					Clickr.snd_PlayEnd.play();
					
					GUI_Cursor.cursor.setCursor(2);
					
					isBonusTime = true;
				}
				
				if (GameTime == 180) Clickr.snd_Alert57.play();	//180 아닌가? 3초니깐...
				
				
				
				if (GameTime == 541) {
					timeWarning = new GUI_TimeWarning_end();
					timeWarning.x = 214 - 3;
					timeWarning.y = 393;
					EffectLevel.addChild(timeWarning);
				}
				
				
					if (GameTime == 600) {	//10초 남기면 GUI_TimeWarning 표시
						Clickr.snd_Alert50.play();	
						effect_Warning = new Effect_Warning();
						effect_Warning.mouseEnabled = false;
						effect_Warning.x = 235;
						effect_Warning.y = 10;
						EffectLevel.addChild(effect_Warning);	//EffectLevel에 addChild?
					}
				
				
				if (GameTime == 3601) {
					
					timeWarning_begin = new GUI_TimeWarning_begin();
					timeWarning_begin.x = 214 - 15;
					timeWarning_begin.y = 393;
					EffectLevel.addChild(timeWarning_begin);
				}
				if (GameTime == 3360) {
					removeObject(timeWarning_begin);
				}
				
				
				if(timeline.width > 0){
					timeline.scaleX = GameTime / 3600;
				}
		
				GameTime--;
				
				
				
			}else if (GameTime == -121) {
				removeObject(effect_Warning);
				
				removeObject(timeWarning);
				
				startBonusTime();
				
				GameTime = -122;
				
				//removeEventListener(Event.ENTER_FRAME, Update);
			}
				
			//timeWarning이 만들어지기 전에 참조해서 null 에러난거임.
			
			time = Math.ceil(GameTime / 60);
			if(time >= 0){
				_countDown.text = time.toString();	//경과시간
				
				if (time < 10) {
					
					timeWarning.setText(int(time));
				}
			}
			
			if (time >= 57 && time <= 60) {
				timeWarning_begin.setText(int(time));
			}
			
			
			//_BlockSpeed.text = BlockMap.BLOCK_DROP_SPEED.toString();
			//_RotSpeed.text = BlockMap.ROT_BLOCKMAP_SPEED.toString();
			
			
			
			
			//0	= Metal Cube : 획득기준 10만점 미만 : Cube Point는 개당 1,000점
			//1	= Bronze Cube : 획득기준 10만점 이상 ~ 50만점 미만 : Cube Point는 개당 5,000점
			//2	= Silver Cube : 획득기준 50만점 이상 ~ 100만점 미만 : Cube Point는 개당 10,000점
			//3	= Gold Cube : 획득기준 100만점 이상 ~ 200만점 미만 : Cube Point는 개당 20,000점
			//4	= Diamond Cube : 획득기준 200만점 이상 ~ : Cube Point는 개당 60,000점
			
			if (BlockMap.SCORE > SCORE_TABLE[signScoreIndex] && !pointSignShown[signScoreIndex]) {
				
				trace("call showPointSign called");
				
				showPointSign(int(signScoreIndex / 9), signScoreIndex % 9);
				
				signScoreIndex++;
			}
			
			
			
			if (BlockMap.SCORE > 100000 && cubeKind == 0) {
				cubeKind++;
				trace("Show Bronze Cube", cubeKind);
				//Show Bronze Cube
				cubeEffect = null;
				cubeEffect = new GUI_Cube_2();
				cubeEffect.x = 104;
				cubeEffect.y = 102.3;
				EffectLevel.addChild(cubeEffect);
			}
				
				
			//큰 수일 땐 안나옴. 뭐임???
			if (BlockMap.SCORE > 500000 && cubeKind == 1) {
				cubeKind++;
				trace("Show Silver Cube", cubeKind);
				//Show Silver Cube
				cubeEffect = null;
				cubeEffect = new GUI_Cube_3();
				cubeEffect.x = 104;
				cubeEffect.y = 102.3;
				EffectLevel.addChild(cubeEffect);
			}
			
			if (BlockMap.SCORE > 1000000 && cubeKind == 2) {
				cubeKind++;
				trace("Show Golden Cube", cubeKind);
				//Show Golden Cube
				cubeEffect = null;
				cubeEffect = new GUI_Cube_4();
				cubeEffect.x = 104;
				cubeEffect.y = 102.3;
				EffectLevel.addChild(cubeEffect);
			}
			
			if (BlockMap.SCORE > 2000000 && cubeKind == 3) {
				cubeKind++;
				trace("Show Dia Cube", cubeKind);
				//Show Diamond Cube
				cubeEffect = null;
				cubeEffect = new GUI_Cube_5();
				cubeEffect.x = 104;
				cubeEffect.y = 102.3;
				EffectLevel.addChild(cubeEffect);
			}
			
		}
		
		private function showPointSign(_kind:int, _num:int) {
			trace("showPointSign called ", _kind, _num);
			
			removeObject(pointSignEffect);
			
			
			switch(_kind) {
				case 0:
				pointSignEffect = new GUI_PointSign_1();
				break;
				case 1:
				pointSignEffect = new GUI_PointSign_2();
				break;
				case 2:
				pointSignEffect = new GUI_PointSign_3();
				break;
			}
			
			pointSignEffect.SetNumber(_num);
			pointSignEffect.x = 103;
			pointSignEffect.y = 205.3;
			
			EffectLevel.addChild(pointSignEffect);
			
			pointSignShown[_kind * 9 + _num] = true;
			
			
			
		}
		
		private function startBonusTime(){
			trace("startBonusTime called");
			
			
			var bonusTime = new Effect_BonusTime();
			bonusTime.x = 430;
			bonusTime.y = 205;
			EffectLevel.addChild(bonusTime);
			
			//보너스타임 애니 끝난 뒤 disptachEvent
			bonusTime.addEventListener(NavigationEvent.BONUS_ANI_END, onAnimationEnd, false, 0, true);
			//타임라인에서 dispatchEvent
			
		}
		private function onAnimationEnd(e:NavigationEvent){
			trace("onAnimationEnd");
			blockMap.dispatchEvent(new CustomEvent(CustomEvent.START_BONUS));
			
			
		}
		
		private function onBonusOver(e:CustomEvent):void{
			//보너스타임 오버 소리 재생
			
			isBonusTime = false;
			
			gameOver = true;
			GUI_Cursor.cursor.setCursor(0);
			
			if (Clickr.bestScored) {
				Clickr.snd_Result_HighScore.play();
				dispatchEvent(new NavigationEvent(NavigationEvent.SHOW_RESULT_HIGH, null, null));
			}else {
				Clickr.snd_Result_Normal.play();
				dispatchEvent(new NavigationEvent(NavigationEvent.SHOW_RESULT, null, null));
			}
			
			
		}
		
		
		
		//해당 오브젝트가 있으면 그 오브젝트를 삭제하고 메모리에서도 삭제한다.
		public function removeObject(_Obj:*) {
			if (_Obj == null) return;
			
			if(this.contains(_Obj)){
				trace(_Obj + " 삭제");
				_Obj.stop();
				MovieClip(_Obj).parent.removeChild(_Obj);
				_Obj = null;
			}
		}
		
		
		
		private function BSUp(e:MouseEvent){
			BlockMap.BLOCK_DROP_SPEED += 20;
		}
		private function BSDown(e:MouseEvent){
			BlockMap.BLOCK_DROP_SPEED -= 20;
		}
		private function RSUp(e:MouseEvent){
			BlockMap.ROT_BLOCKMAP_SPEED += 20;
		}
		private function RSDown(e:MouseEvent){
			BlockMap.ROT_BLOCKMAP_SPEED -= 20;
		}
		
		
		private function onDoubleChance(e:CustomEvent) {
			trace("더블찬스이벤트", e.type);
			switch(e.type) {
				case "doubleChanceStart" :
				trace("Start");
				doubleChanceEffect = new GUI_DoubleChance_on();
				doubleChanceEffect.x = 429.4;
				doubleChanceEffect.y = 447.3
				EffectLevel.addChild(doubleChanceEffect);
				GUI_Cursor.cursor.setCursor(1)
				break;
				case "doubleChanceSuccess" :
				trace("Success");
				removeObject(doubleChanceEffect);
				
				doubleChanceEffect = new GUI_DoubleChance_success();
				doubleChanceEffect.x = 429.4;
				doubleChanceEffect.y = 447.3
				EffectLevel.addChild(doubleChanceEffect);
				GUI_Cursor.cursor.setCursor(0);
				break;
				case "doubleChanceFail" :
				trace("Fail");
				removeObject(doubleChanceEffect);
				
				doubleChanceEffect = new GUI_DoubleChance_fail();
				doubleChanceEffect.x = 429.4;
				doubleChanceEffect.y = 447.3
				EffectLevel.addChild(doubleChanceEffect);
				GUI_Cursor.cursor.setCursor(0);
				break;
			}
		}
		
		public function onClickPause(e:MouseEvent = null) {
			//GameTime이 0 이상이어야만
			if (GameTime > 0) {
				dispatchEvent(new NavigationEvent(NavigationEvent.PAUSE, "PointC"));
				//isPaused = true;
			}
			trace("InGame onClickPause ", isPaused);
		}
		
		
		public function onClickRetry(e:MouseEvent) {
			
			
			dispatchEvent(new NavigationEvent(NavigationEvent.RESTART, "PointC"));
		}
		
		private function onRequestRestart(e:NavigationEvent) {
			
			
			dispatchEvent(new NavigationEvent(NavigationEvent.RESTART, "PointC"));
		}
		
		private function onClickRotateL(e:MouseEvent) {
			if(GameTime > 0){
				blockMap.dispatchEvent(new CustomEvent(CustomEvent.ROTATE_LEFT));
			}
		}
		
		private function onClickRotateR(e:MouseEvent) {
			if(GameTime > 0){
				blockMap.dispatchEvent(new CustomEvent(CustomEvent.ROTATE_RIGHT));
			}
		}
		private function onRequestRotateL(e:CustomEvent) {
			RotateL.gotoAndPlay("Push");
			//BlockMap.dispatchEvent(new CustomEvent(CustomEvent.ROTATE_RIGHT));
		}
		private function onRequestRotateR(e:CustomEvent) {
			RotateR.gotoAndPlay("Push");
			//BlockMap.dispatchEvent(new CustomEvent(CustomEvent.ROTATE_RIGHT));
		}
		
		private function comboPlusHandler(e:CustomEvent) {
			
			comboPlus.gotoAndPlay(2);
			
			
			
		}
		
		
		private function scoreUp(e:CustomEvent){
			//올라가는 연출
			//BlockMap.SCORE에 따라 점수 상승 속도 결정
			if(GameTime == -90){	//보너스 타임 시에는 6
				scoreUPS = 10 * Math.pow(6, Math.log(e.upScore) * Math.LOG10E);
			}else{
				scoreUPS = 10 * Math.pow(5, Math.log(e.upScore) * Math.LOG10E);
			}
			
			
			//scoreUPS / 60 만큼 올라감
			scoreCopy = BlockMap.SCORE - e.upScore;
			
			
			addEventListener(Event.ENTER_FRAME, scoreUpEF, false, 0, true);
			
			//PC_PointSign1.wav : 포인트사인 1단계 (500~70,000)
    		//PC_PointSign2.wav : 포인트사인 2단계 (100,000~900,000)
    		//PC_PointSign3.wav : 포인트사인 3단계 (1,000,000~5,000,000)
        	//소리 길이에 맞춰 포인트사인이미지 연출시간 조정 가능.
			//snd_PointSign1
			
			
			if(e.upScore <= 1000){
				Clickr.snd_PointUp1.play();
			}else if(1000 < e.upScore && e.upScore <= 20000){
				Clickr.snd_PointUp2.play();
			}else if(20000 < e.upScore){
				Clickr.snd_PointUp3.play();
			}
			
			
		}
		
		private function scoreUpEF(e:Event){
			
			if(scoreCopy < BlockMap.SCORE){
				scoreCopy += scoreUPS / 60;
			}else{
				scoreCopy = BlockMap.SCORE;
				removeEventListener(Event.ENTER_FRAME, scoreUpEF);
				
			}
			
			scoreTXT.text = Clickr.makeCurrency(scoreCopy);
			
			if (BlockMap.SCORE >= Clickr.bestScore) {
				
				bestScoreTXT.textColor = 0xFFC24C;
				
				bestScoreTXT.text = Clickr.makeCurrency(scoreCopy);
				
				//Clickr.bestScore = BlockMap.SCORE;
				Clickr.bestScored = true;
				
				
			}
			
			
			
			
		}
		
	}
}